package com.turing.usdtpay.mvp.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Messenger;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.turing.usdtpay.R;
import com.turing.usdtpay.base.BaseFragment;
import com.turing.usdtpay.entity.NoticeData;
import com.turing.usdtpay.entity.OrderInfoData;
import com.turing.usdtpay.entity.RobData;
import com.turing.usdtpay.mvp.activity.BuyOrderActivity;
import com.turing.usdtpay.mvp.activity.NoticeActivity;
import com.turing.usdtpay.mvp.activity.SellOrderActivity;
import com.turing.usdtpay.mvp.contract.RobOrderContract;
import com.turing.usdtpay.mvp.presenter.RobOrderPresenter;
import com.turing.usdtpay.service.PushService;
import com.turing.usdtpay.utils.FormatUtils;
import com.turing.usdtpay.utils.LogUtils;
import com.turing.usdtpay.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @作者：JAY
 * @创建时间：2019/10/10 11:06
 * @描述：
 **/
public class RobOrderFragment extends BaseFragment implements RobOrderContract.View {
    private String TAG = "RobOrderFragment";
    private Button mBuy, mSell;
    private TextView mSetting, mNotice, mBuyGoing, mSellGoing, mNewBuy, mNewSell;
    private RobOrderContract.Present mPresent;
    private TextView mDayProfit, mTotalProfit, mDayCount, mDayDeal;
    private boolean canDeal, isAuth;
    private boolean isBuy = false, isSell = false;  //判断是否停止请求订单
    private boolean needBuyOrder = false, needSellOrder = false;  //判断是否需要请求订单信息
    private int mStatus = 0;
    private int mCurrent = 0;
    private ArrayList<NoticeData> mNoticeList = new ArrayList<>();
    private RunThread mThread = null;
    private boolean isRunning = false;
    private TextView mCanSell;
    private String mCanSellMin ="0";
    private String mCanSellMax = "0";
    private boolean hasHandleSell, hasHandleBuy;  //判断是否有买卖订单存在
    private double mMoney = 0;

    public static RobOrderFragment newInstance(Bundle bundle) {
        RobOrderFragment fragment = new RobOrderFragment();
        if (bundle != null) {
            fragment.setArguments(bundle);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setPresenter(new RobOrderPresenter(this));
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LogUtils.d(TAG, "onCreateView");
        View view = inflater.inflate(R.layout.fragment_rob, container, false);
        initView(view);
        initData();
        return view;
    }

    private void initData() {
        showProgressBar(true);
        mPresent.getMoney(getActivity());
        mPresent.startServer(getActivity().getApplicationContext());
    }

    private void initView(View view) {
        mBuy = (Button) view.findViewById(R.id.btn_buy);
        mSell = (Button) view.findViewById(R.id.btn_sell);
        mSetting = (TextView) view.findViewById(R.id.tv_setting);
        mNotice = (TextView) view.findViewById(R.id.tv_notice);
        mBuyGoing = (TextView) view.findViewById(R.id.tv_buy_going);
        mSellGoing = (TextView) view.findViewById(R.id.tv_sell_going);
        mNewBuy = (TextView) view.findViewById(R.id.tv_new_buy);
        mNewSell = (TextView) view.findViewById(R.id.tv_new_sell);
        mDayProfit = (TextView) view.findViewById(R.id.day_profit);
        mTotalProfit = (TextView) view.findViewById(R.id.total_profit);
        mDayCount = (TextView) view.findViewById(R.id.day_count);
        mDayDeal = (TextView) view.findViewById(R.id.day_deal);
        mCanSell = (TextView) view.findViewById(R.id.tv_can_sell);
        mBuy.setOnClickListener(this);
        mSell.setOnClickListener(this);
        mSetting.setOnClickListener(this);
        mNotice.setSelected(true);
        mNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == mBuy.getId()) {
            if (!canDeal) {
                ToastUtils.showNormolToast(getActivity(), "不可交易");
                return;
            }
            if (!isAuth) {
                ToastUtils.showNormolToast(getActivity(), "请实名认证");
                return;
            }
            if (needBuyOrder) {
                mPresent.getOrderInfo(getActivity(),1);
                return;
            }
            if (hasHandleSell) {
                ToastUtils.showNormolToast(getActivity(), "必须先处理完当前订单才能抢买");
                return;
            }
            showProgressBar(true);
            if (!isBuy) {
                mPresent.buyOrder(getActivity());
            } else {
                mPresent.stopBuy(getActivity());
            }

        } else if (v.getId() == mSell.getId()) {
            if (!canDeal) {
                ToastUtils.showNormolToast(getActivity(), "不可交易");
                return;
            }
            if (!isAuth) {
                ToastUtils.showNormolToast(getActivity(), "请实名认证");
                return;
            }
            if (needSellOrder) {
                mPresent.getOrderInfo(getActivity(),2);
                return;
            }
            if (hasHandleBuy) {
                ToastUtils.showNormolToast(getActivity(), "必须先处理完当前订单才能抢卖");
                return;
            }
            showProgressBar(true);
            if (!isSell) {
                mPresent.sellOrder(getActivity());
            } else {
                mPresent.stopSell(getActivity());
            }
        } else if (v.getId() == mSetting.getId()) {
            openNewFragment(RobSettingFragment.newInstance(null));
        } else if (v.getId() == mNotice.getId()) {
            if (mCurrent == 0) {
                Intent intent = new Intent(getActivity(), NoticeActivity.class);
                intent.putExtra("title", mNoticeList.get(mCurrent).getTitle());
                intent.putExtra("id", mNoticeList.get(mCurrent).getId());
                startActivity(intent);
            } else {
                Intent intent = new Intent(getActivity(), NoticeActivity.class);
                intent.putExtra("title", mNoticeList.get(mCurrent - 1).getTitle());
                intent.putExtra("id", mNoticeList.get(mCurrent - 1).getId());
                startActivity(intent);
            }

        }
    }

    private void robOrder(Activity activity, Button button, TextView going, TextView tip) {
        if (getActivity() == null) {
            return;
        }
        button.setTextColor(activity.getResources().getColor(R.color.colorBlack));
        button.setText("停止");
        button.setBackgroundResource(R.drawable.btn_gray_bg);
        going.setVisibility(View.VISIBLE);
        tip.setVisibility(View.GONE);
    }

    private void handleOrder(Activity activity, Button button, TextView going, TextView tip) {
        if (getActivity() == null) {
            return;
        }
        button.setTextColor(activity.getResources().getColor(R.color.colorWhite));
        button.setText("去处理");
        button.setBackgroundResource(R.drawable.btn_blue_bg);
        going.setVisibility(View.GONE);
        tip.setVisibility(View.VISIBLE);
        mCanSell.setVisibility(View.GONE);
    }

    private void normalState() {
        if (getActivity() == null) {
            return;
        }
        mBuy.setText("一键买入");
        mBuy.setBackgroundResource(R.drawable.btn_green_bg);
        mBuy.setTextColor(getActivity().getResources().getColor(R.color.colorWhite));
        mSell.setText("一键卖出");
        mSell.setBackgroundResource(R.drawable.btn_red_bg);
        mSell.setTextColor(getActivity().getResources().getColor(R.color.colorWhite));
        mBuyGoing.setVisibility(View.GONE);
        mSellGoing.setVisibility(View.GONE);
        mNewBuy.setVisibility(View.GONE);
        mNewSell.setVisibility(View.GONE);
        mCanSell.setVisibility(View.GONE);
    }


    @Override
    public void buying() {
        showProgressBar(false);
        isBuy = true;
        robOrder(getActivity(), mBuy, mBuyGoing, mNewBuy);
    }

    @Override
    public void selling(String limit) {
        String[] split = limit.split("\\|");
        mCanSellMin = FormatUtils.NoumberFromat2((Double.parseDouble(split[0])/100));
        mCanSellMax = FormatUtils.NoumberFromat2((Double.parseDouble(split[1])/100));
        if (mMoney <(Double.parseDouble(split[0])/100) || mMoney <0){
            mPresent.stopSell(getActivity());
            ToastUtils.showNormolToast(getActivity(),"可用余额不足");
            return;
        }
        showProgressBar(false);
        String s = "";
        if (mMoney > (Double.parseDouble(split[1])/100)){
            s = "抢卖金额<font color='#ff0000'>" + mCanSellMin + "-" + mCanSellMax + "</font>CNY";
        }else {
            s = "抢卖金额<font color='#ff0000'>" + mCanSellMin + "-" + FormatUtils.NoumberFromat2(mMoney) + "</font>CNY";
        }
        mCanSell.setText(Html.fromHtml(s));
        mCanSell.setVisibility(View.VISIBLE);
        isSell = true;
        robOrder(getActivity(), mSell, mSellGoing, mNewSell);
    }

    @Override
    public void stopTrader(int type) {
        showProgressBar(false);
        hasHandleBuy = false;
        hasHandleSell = false;
        isSell = false;
        isBuy = false;
        normalState();
    }


    @Override
    public void getStateSuccess(RobData data) {
        showProgressBar(false);
        mDayProfit.setText(FormatUtils.NoumberFromat2((double) data.getDay_commission() / 100));
        mTotalProfit.setText("累计收益" + FormatUtils.NoumberFromat2((double) data.getCount_commission() / 100) + "元");
        mDayCount.setText(data.getDay_order_num() + "");
        String sell_info = data.getSell_info();
        if (!TextUtils.isEmpty(sell_info)){
            String[] split = sell_info.split("\\|");
            mCanSellMin = FormatUtils.NoumberFromat2((Double.parseDouble(split[0])/100));
            mCanSellMax = FormatUtils.NoumberFromat2((Double.parseDouble(split[1])/100));
            String s = "";
            if (mMoney > (Double.parseDouble(split[1])/100)){
                s = "抢卖金额<font color='#ff0000'>" + mCanSellMin + "-" + mCanSellMax + "</font>CNY";
            }else {
                s = "抢卖金额<font color='#ff0000'>" + mCanSellMin + "-" + FormatUtils.NoumberFromat2(mMoney) + "</font>CNY";
            }
            mCanSell.setText(Html.fromHtml(s));
        }

        mDayDeal.setText(FormatUtils.NoumberFromat2((double) data.getDay_count_money() / 100));
        if (data.getCan_trade() == 1) {
            canDeal = true;
        }
        if (data.getIs_check() == 1) {
            isAuth = true;
        }
        mStatus = data.getCur_status();
        if (mStatus == 1) {
            isBuy = true;
            needBuyOrder = false;
            hasHandleSell = false;
            hasHandleBuy = true;
            robOrder(getActivity(), mBuy, mBuyGoing, mNewBuy);
        } else if (mStatus == 2) {
            needBuyOrder = true;
            hasHandleSell = false;
            hasHandleBuy = true;
            handleOrder(getActivity(), mBuy, mBuyGoing, mNewBuy);
        } else if (mStatus == 3) {
            mCanSell.setVisibility(View.VISIBLE);
            isSell = true;
            needSellOrder = false;
            hasHandleSell = true;
            hasHandleBuy = false;
            robOrder(getActivity(), mSell, mSellGoing, mNewSell);
        } else if (mStatus == 4) {
            needSellOrder = true;
            hasHandleSell = true;
            hasHandleBuy = false;
            handleOrder(getActivity(), mSell, mSellGoing, mNewSell);
        } else if (mStatus == 0) {
            needSellOrder = false;
            needBuyOrder = false;
            hasHandleSell = false;
            hasHandleBuy = false;
            normalState();
        }

        List<NoticeData> notices = data.getNotices();
        sortNotice(notices);
        if (mThread == null) {
            mThread = new RunThread();
            LogUtils.d("Thread start");
            isRunning = true;
            mThread.start();
        }
    }


    @Override
    public void onDestroyView() {
        LogUtils.d("onDestroyView");
        if (mThread != null) {
            isRunning = false;
            mThread.interrupt();
            LogUtils.d("onDestroy Thread.interrupt()" + mThread.isInterrupted());
            mThread = null;
        }
        super.onDestroyView();
    }

    @Override
    public void onFail(String error) {
        showProgressBar(false);
        ToastUtils.showNormolToast(getActivity(), error);
    }

    @Override
    public void getOrder(OrderInfoData data , int type) {
        if (type == 1){
            Intent intent = new Intent(getActivity(), BuyOrderActivity.class);
            intent.putExtra("data",data);
            startActivityForResult(intent,1000);
        }else {
            Intent intent = new Intent(getActivity(), SellOrderActivity.class);
            intent.putExtra("data",data);
            startActivityForResult(intent,2000);
        }

    }


    @Override
    public void serviceResult(int type) {
        if (getActivity() == null){
            return;
        }
        if (type == 0){
            needBuyOrder = false;
            needSellOrder = false;
            mPresent.getState(getActivity());
        }else if (type == 1){
            isBuy = true;
            needBuyOrder = false;
            hasHandleSell = false;
            hasHandleBuy = true;
            robOrder(getActivity(), mBuy, mBuyGoing, mNewBuy);
        }else if (type == 2){
            needBuyOrder = true;
            hasHandleSell = false;
            hasHandleBuy = true;
            handleOrder(getActivity(), mBuy, mBuyGoing, mNewBuy);
        } else if (type == 3){
            isSell = true;
            needSellOrder = false;
            hasHandleSell = true;
            hasHandleBuy = false;
            robOrder(getActivity(), mSell, mSellGoing, mNewSell);
        } else if (type == 4){
            needSellOrder = true;
            hasHandleSell = true;
            hasHandleBuy = false;
            handleOrder(getActivity(), mSell, mSellGoing, mNewSell);
        }
    }

    @Override
    public void getMoneySuccess(int money) {
        mMoney = (double)money/100;
        mPresent.getState(getActivity());
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000&&resultCode == 1){
            mPresent.getState(getActivity());
        }else if (requestCode == 2000&&resultCode == 2){
            mPresent.getState(getActivity());
        }
    }

    @Override
    public void setPresenter(RobOrderContract.Present presenter) {
        mPresent = presenter;
    }

    private void sortNotice(List<NoticeData> list) {
        mNoticeList.clear();
        Object[] array = list.toArray();
        Arrays.sort(array);
        for (int i = 0; i < array.length; i++) {
            mNoticeList.add((NoticeData) array[i]);
        }
        LogUtils.d("noticeList ->" + mNoticeList);
    }

    /**
     * 循环显示公告
     */
    public class RunThread extends Thread {

        @Override
        public void run() {
            super.run();
            while (isRunning) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mNoticeList.size() != 0) {
                                if (mCurrent == mNoticeList.size()) {
                                    mCurrent = 0;
                                    mNotice.setText(mNoticeList.get(mCurrent).getTitle());
                                } else {
                                    mNotice.setText(mNoticeList.get(mCurrent).getTitle());
                                    mCurrent = ++mCurrent;
                                }
                            }
                        }
                    });
                    try {
                        Thread.sleep(3500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        isRunning = false;
                    }
                }
            }
        }
    }
}
